<script setup lang='ts'>
import { ref, onMounted, watch } from "vue"
import { getAllCategoryInfo, getThirdCategoryInfo, getInitCategoryBookInfo, getCategoryBookInfo } from "@/api/index"
import { useRouter } from "vue-router";
import BookViewFifth from "@/components/BookViewFifth.vue"
import LoadingPage from "@/components/LoadingPage.vue";
import LoadingView from "@/components/LoadingView.vue";

const $router = useRouter()
const categoryList = ref<any>()
const initCategoryBooks = ref<any>()

const catId = ref<string>()
const isloading = ref<boolean>(true)
const isShowLoadingView = ref<boolean>(false)
onMounted(async () => {
    let res = await getAllCategoryInfo()
    categoryList.value = res.data
    secondCategory.value = categoryList.value[0].cates[0].name
    secondCategoryList.value = categoryList.value[0].cates

    let thirdCategoryRes = await getThirdCategoryInfo(secondCategoryList.value[0].url)

    thirdCategoryList.value = thirdCategoryRes.data.categories
    thirdCategory.value.sore = thirdCategoryList.value[3].catArray[0].name
    thirdCategory.value.pay = thirdCategoryList.value[0].catArray[0].name
    thirdCategory.value.bookStatus = thirdCategoryList.value[1].catArray[0].name
    thirdCategory.value.wordCount = thirdCategoryList.value[2].catArray[0].name
    thirdCategory.value.subCat = '全部'
    catId.value = subCatId(secondCategoryList.value[0].url)
    let initCategoryBooksRes = await getInitCategoryBookInfo(catId.value, page_num.value);
    initCategoryBooks.value = initCategoryBooksRes.data.list

    isloading.value = false
})
const subCatId = (str: any) => {
    return str.slice(26)

}
const firstCategory = ref<string>('男生')
const secondCategory = ref<string>('')
const secondCategoryList = ref<any>()
const thirdCategory = ref<any>({})
const thirdCategoryList = ref<any>()
const changeFirstCategory = async (c: any) => {
    firstCategory.value = c.name
    isShowLoadingView.value = true

    let category = 0
    if (c.name == '男生') {
        category = 0
    } else if (c.name == '女生') {
        category = 1
    } else if (c.name == '出版') {
        category = 2
    } else if (c.name == '听书') {
        category = 3
    }
    //二级索引样式
    secondCategory.value = categoryList.value[category].cates[0].name
    secondCategoryList.value = categoryList.value[category].cates

    //二级索引对应的书籍数据
    let thirdCategoryRes = await getThirdCategoryInfo(secondCategoryList.value[0].url)

    thirdCategoryList.value = thirdCategoryRes.data.categories

    catId.value = subCatId(secondCategoryList.value[0].url)  //选择一级索引时改变当前分类catId
    page_num.value = 1
    initCategoryBooks.value = await clickToChangeBookList()

    isShowLoadingView.value = false

}
const changeSecondCategory = async (item: any) => {
    isShowLoadingView.value = true

    secondCategory.value = item.name
    catId.value = subCatId(item.url)
    page_num.value = 1
    initCategoryBooks.value = await clickToChangeBookList()
    isShowLoadingView.value = false

}
const showThirdCategory = ref<boolean>(false)
const toShowThirdCategory = () => {
    showThirdCategory.value = !showThirdCategory.value

}
const toBookDetail = (book: any) => {
    if (firstCategory.value == '听书') {
        $router.push({ path: '/book-listen', query: { id: book.id } })
    } else {
        $router.push({ path: '/detail', query: { id: book.id, title: book.title } })
    }
}

//触底加载
const loading = ref<boolean>(false)
const finished = ref<boolean>(false)
const isLoading = ref<boolean>(false)
const page_num = ref<number>(1)
const onLoad = async () => {
    page_num.value += 1

    if (!isLoading.value) {
        isLoading.value = true
        let res = await clickToChangeBookList()
        initCategoryBooks.value = [...initCategoryBooks.value, ...res]
        loading.value = false
        isLoading.value = false
    }
}

const changeThirdCategory = async (i: any, c: any) => {
    isShowLoadingView.value = true
    if (i.type == 'pay') {
        thirdCategory.value.pay = c
    } else if (i.type == 'bookStatus') {
        thirdCategory.value.bookStatus = c
    } else if (i.type == 'wordCount') {
        thirdCategory.value.wordCount = c
    } else if (i.type == 'subCat') {
        thirdCategory.value.subCat = c
    }
    page_num.value = 1
    initCategoryBooks.value = await clickToChangeBookList()
    isShowLoadingView.value = false

}

const clickToChangeBookList = async () => {
    let currentSore = thirdCategoryList.value.filter((i: any) => i.type == 'sort')[0].catArray.findIndex((o: any) =>
        o.name == thirdCategory.value.sore
    )
    currentSore = currentSore == 1 ? 3 : 1
    let currentPay = thirdCategoryList.value.filter((i: any) => i.type == 'pay')[0].catArray.findIndex((o: any) =>
        o.name == thirdCategory.value.pay
    )
    currentPay = currentPay ? currentPay : 0
    let currentBookStatus = thirdCategoryList.value.filter((i: any) => i.type == 'bookStatus')[0]?.catArray.findIndex((o: any) =>
        o.name == thirdCategory.value.bookStatus
    )
    currentBookStatus = currentBookStatus ? currentBookStatus : 0
    let currentWordCount = thirdCategoryList.value.filter((i: any) => i.type == 'wordCount')[0]?.catArray.findIndex((o: any) =>
        o.name == thirdCategory.value.wordCount
    )
    currentWordCount = currentWordCount ? currentWordCount : 0
    let res = await getCategoryBookInfo(catId.value, currentWordCount, currentPay, currentBookStatus, currentSore, page_num.value)
    return res.data.list
}

const changeThirdCategorySore = async (str: string) => {
    isShowLoadingView.value = true
    page_num.value = 1
    thirdCategory.value.sore = str;
    initCategoryBooks.value = await clickToChangeBookList()
    isShowLoadingView.value = false
}
const moveStart = ref<number>(0)
const moveEnd = ref<number>(0)
const showFirstCategory = ref<boolean>(true)


const getTouchstartY = (event: any) => {
    moveStart.value = event?.changedTouches[0]?.pageY

}

const touchmove = (event: any) => {

    moveEnd.value = event?.changedTouches[0]?.pageY
    if (moveStart.value - moveEnd.value > 120) {
        showFirstCategory.value = false
        showThirdCategory.value = false

    } else if (moveEnd.value - moveStart.value > 120) {
        // console.log('展示起来');
        showFirstCategory.value = true
    }

}
</script>

<template>
    <div :style="{ height: '100%', width: '100%' }">
        <LoadingView v-if="isShowLoadingView" />
        <LoadingPage v-if="isloading" />
        <div class="category" v-else @touchstart="getTouchstartY" @touchmove="touchmove">
            <Transition name="firstCategory">
                <div class="category-first" v-if="showFirstCategory">

                    <ul class="list">
                        <li v-for="c, index in categoryList" :key="index" :class="{ active: firstCategory == c.name }"
                            @click="changeFirstCategory(c)">{{
                                c.name
                            }}
                        </li>
                    </ul>
                    <img src="@/assets/imgs/搜索1.png" alt="" @click.stop="$router.push('/search')">
                </div>
            </Transition>

            <div class="category-second">
                <ul class="list">
                    <li v-for="item, index in secondCategoryList" :key="index"
                        :class="{ active: item.name == secondCategory }" @click.stop="changeSecondCategory(item)">
                        <span>{{ item.name }}</span>
                        <span></span>
                    </li>
                </ul>
            </div>
            <div class="category-third">
                <div class="title">
                    <div class="left">
                        <span :class="{ active: thirdCategory.sore == '畅销' }"
                            @click="changeThirdCategorySore('畅销')">畅销</span>
                        <span :class="{ active: thirdCategory.sore == '最新' }"
                            @click="changeThirdCategorySore('最新')">最新</span>
                    </div>
                    <div class="right">
                        <span @click.stop="toShowThirdCategory">筛选</span>
                    </div>
                </div>
                <ul class="category-third-detail" v-if="showThirdCategory">
                    <li v-for="i, index in thirdCategoryList" :key="index">
                        <ul class="list" v-if="i.type != 'sort'">
                            <li v-for="c, index in i.catArray" :key="index">
                                <span
                                    :class="{ active: (i.type == 'pay' && thirdCategory.pay == c.name) || (thirdCategory.bookStatus == c.name && i.type == 'bookStatus') || (thirdCategory.wordCount == c.name && i.type == 'wordCount') || (thirdCategory.subCat == c.name && i.type == 'subCat') }"
                                    @click="changeThirdCategory(i, c.name)">{{
                                        c.name
                                    }}</span>
                                <span v-if="index < i.catArray.length - 1">&nbsp; · &nbsp;</span>
                            </li>
                        </ul>
                    </li>


                </ul>
            </div>
            <div class="book-list">
                <van-list v-model:loading="loading" :finished="finished" :immediate-check="false" :offset="1"
                    finished-text="没有更多了" loading-text="数据加载中" error-text="加载失败" @load="onLoad">
                    <div class="category-book">
                        <BookViewFifth v-for="book in initCategoryBooks" :key="book.id" :book="book"
                            @click.stop="toBookDetail(book)" />
                    </div>
                </van-list>
            </div>
        </div>
    </div>
</template>

<style lang="less" scoped>
.firstCategory-leave-from,
.firstCategory-enter-to {
    transform: translateY(0);
}

.firstCategory-leave-active,
.firstCategory-enter-active {
    transition: all 0.2s;
}

.firstCategory-leave-to,
.firstCategory-enter-from {
    transform: translateY(-50rem);
}

.category {
    width: 100vw;
    height: 100%;
    display: flex;
    flex-direction: column;
    // transition: all 0.2s;

    .category-first {
        flex-shrink: 0;
        height: 50rem;
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 20rem;
        // transition: all 0.2s;

        ul.list {
            height: 100%;
            display: flex;
            justify-content: left;
            align-items: center;

            li {
                margin-right: 20rem;

                &.active {
                    font-size: 17rem;
                    font-weight: bold;
                }
            }
        }

        img {
            width: 25rem;
            height: 25rem;
        }
    }

    .category-second {
        ul.list {
            padding: 15rem 20rem 5rem;
            background-color: #eee;
            display: flex;
            flex-wrap: wrap;
            justify-content: left;

            li {
                margin-right: 19rem;
                margin-bottom: 10rem;
                display: flex;
                flex-direction: column;
                align-items: center;

                span {
                    font-size: 14rem;
                    color: #2d2d2d;

                    &:last-child {
                        display: flex;
                        width: 10rem;
                        height: 2rem;
                        background-color: #eee;
                    }
                }

                &.active {
                    span {
                        color: #fc1c1c;

                        &:last-child {
                            background-color: #fc1c1c;
                        }
                    }
                }
            }
        }
    }

    .category-third {
        color: #2d2d2d;
        padding: 10rem 20rem 10rem;

        .title {
            display: flex;
            justify-content: space-between;

            .left {
                span {
                    font-size: 14rem;
                    color: #2d2d2d;

                    &.active {
                        color: #fc1c1c;
                    }

                    &:first-child {
                        padding-right: 10rem;
                        border-right: 2rem solid#888;
                    }

                    &:last-child {
                        margin-left: 10rem;
                    }
                }
            }

            .right {
                span {
                    font-size: 14rem;
                    border: 1rem solid#ccc;
                    padding: 2rem 5rem;
                    border-radius: 10rem;
                }
            }
        }

        ul.category-third-detail {
            transition: all 0.2s;
            margin-top: 10rem;

            >li {
                // margin-bottom: 10rem;

                ul.list {
                    display: flex;
                    flex-wrap: wrap;

                    li {
                        display: flex;
                        flex-wrap: wrap;
                        margin-bottom: 10rem;

                        span {
                            font-size: 14rem;
                            color: #2d2d2d;

                            &.active {
                                color: #fc1c1c;
                            }
                        }
                    }
                }
            }
        }
    }

    .book-list {
        flex-grow: 1;
        overflow: auto;

        .category-book {
            height: 100%;
            padding: 0 20rem 0;
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
        }
    }
}
</style>
